<template>
  <div class="dashboard-editor-container">
    <el-row style="width: 86.3%; top: 6px; z-index: 999; position: fixed">
      <el-col :span="17">
        <nav id="navbar">
          <ul></ul>
        </nav>
      </el-col>
      <!-- <el-col :span="7">
        <date
          v-model="valueTime"
          :type.sync="groupType"
          @handleChangeTime="handleChangeTime($event)"
        ></date>
      </el-col> -->
    </el-row>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="" prop="orderId">
        <el-select
          v-model="queryParams.brandList"
          placeholder="请选择品牌"
          multiple
          filterable
          @change="changebrandList"
        >
          <el-option
            v-for="(item, index) in brandList"
            :key="index"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="orderId">
        <el-select
          v-model="queryParams.liveTypeList"
          placeholder="自播/达播"
          clearable
          multiple
          filterable
        >
          <el-option
            v-for="item in liveTypeList"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="orderId">
        <el-select
          v-model="queryParams.channelList"
          placeholder="请选择渠道"
          clearable
          multiple
          filterable
        >
          <el-option
            v-for="(item, index) in channelList"
            :key="index"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="" prop="orderId">
        <el-select
          v-model="queryParams.shopList"
          placeholder="请选择店铺"
          clearable
          multiple
          filterable
        >
          <el-option
            v-for="(item, index) in shopList"
            :key="index"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="getautoSelectProTypeList"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        <el-button type="primary" size="mini" @click="openInfo = true"
          >品类配置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row
      :gutter="10"
      style="background: #fff; margin-bottom: 16px"
      v-for="(item, index) in list"
      :key="index"
    >
      <el-card>
        <div
          slot="header"
          style="justify-content: space-between; display: flex"
        >
          <!-- {{ item.salesGrade.join("-")
            }}{{ " " + item.liveType ? item.liveType : "综合" }} -->
          <span><i class="el-icon-collection"></i>{{ item.titleName }} </span>
          <span>
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExportCheckCost(item.salesGrade, item.liveType)"
              >导出</el-button
            >
          </span>
        </div>
        <el-table :data="item.biLiveTalentVolist" :height="400">
          <el-table-column
            label="品类"
            align="center"
            prop="productType"
          ></el-table-column>
          <el-table-column label="销售总金额" align="center" prop="payAmount" />
          <!-- <el-table-column
              label="销售订单数 "
              align="center"
              prop="orderQuantity"
            ></el-table-column> -->
          <el-table-column
            label="销售总件数"
            align="center"
            prop="productQuantity"
          />
          <el-table-column
            label="退款总金额"
            align="center"
            prop="returnAmount"
          />
          <el-table-column
            label="净销售金额"
            align="center"
            prop="netSaleAmount"
          />
          <el-table-column
            label="退货件数"
            align="center"
            prop="returnQuantity"
          />
          <el-table-column
            label="净销售成本"
            align="center"
            prop="netSaleCost"
          />
          <el-table-column
            label="销售零售总额"
            align="center"
            prop="retailAmount"
          />
          <el-table-column
            label="退货零售总额"
            align="center"
            prop="retailReturnAmount"
          />
          <el-table-column
            label="综合退款率"
            align="center"
            prop="returnRateStr"
          />
          <el-table-column
            label="折扣率"
            align="center"
            prop="discountRateStr"
          />
        </el-table>
        <!-- <pagination
          v-show="item.total > 0"
          :total="item.total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          :page-sizes="[5, 10, 30, 50, 100]"
          @pagination="getautoSelectProTypeList"
        /> -->
      </el-card>
    </el-row>

    <el-dialog
      :visible.sync="openInfo"
      width="1500px"
      append-to-body
      v-if="openInfo"
    >
      <div class="el-dialog-div">
        <component :is="'ProTypeConf'"></component>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAll, importBiKeyword } from "@/api/chart/brandChannelShop";
import axios from "axios";
//--------导入token
import { getToken } from "@/utils/auth";
import {
  listBiLiveTalent,
  getBiLiveTalent,
  delBiLiveTalent,
  addBiLiveTalent,
  updateBiLiveTalent,
  synTalentData,
} from "@/api/live/BiLiveTalent";
import date from "./day/date.vue";
import ProTypeConf from "@/views/conf/ProTypeConf/index.vue";
import {
  selectLiveData,
  selectLiveOrderSaleList,
  selectLiveSaleStatistics,
  selectProTypeList,
  BiLiveCheckCost,
  BiLiveCheckCostlist,
  delBiLiveCheckCost,
  autoSelectProTypeList,
} from "@/api/live/BiLiveOrder";
export default {
  name: "BiLiveTalent",
  props: {
    timeObj: {
      type: Object,
      default: () => {},
    },
  },
  components: {
    date,
    ProTypeConf,
  },
  data() {
    return {
      openInfo: false,
      list: [],
      brandList: [],
      channelList: [],
      shopList: [],
      liveTypeList: ["自播", "达播", "综合"],
      cascadeList: [],
      //时间控件
      valueTime: new Date(new Date().setDate(new Date().getDate() - 1)),
      groupType: "date",
      // timeObj: {},

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 达人直播订单表格数据
      BiLiveTalentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderId: null,
        talentName: null,
        talentId: null,
        commissionRate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    // this.getList();
    this.getdataSourceList();
  },
  watch: {
    queryParams: {
      handler: function (newnew, oldold) {
        this.getautoSelectProTypeList();
      },
      deep: true,
      immediate: true,
    },
    timeObj: {
      handler: function (newnew, oldold) {
        this.getautoSelectProTypeList();
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    handleGo(path) {
      this.$router.push(path);
    },
    changebrandList() {
      if (this.queryParams.brandList.length == 0) {
        this.$modal.msgError("请选择至少一个品牌");
        this.queryParams.brandList = this.brandList;
      }
    },
    getautoSelectProTypeList() {
      let obj = {
        ...this.timeObj,
        ...this.queryParams,
      };
      this.openLoading();
      autoSelectProTypeList(obj).then((response) => {
        this.$modal.closeLoading();
        this.list = response;
      });
    },
    // 打开加载层
    openLoading() {
      this.$modal.loading("正在加载数据，请稍候！");
    },
    handleChangeTime(timeObj) {
      // console.log(type)
      // console.log(timeObj)
      // TODO
      this.timeObj = timeObj;
    },
    /** 查询品牌渠道店铺关系列表 */
    getdataSourceList() {
      listAll().then((response) => {
        let list = [];
        response.forEach((item) => {
          if (item.isTalentLive == "是") {
            list.push(item);
          }
        });
        this.brandList = [...new Set(list.map((item) => item.brand))];
        this.channelList = [...new Set(list.map((item) => item.channel))];
        this.shopList = [...new Set(list.map((item) => item.channelShopName))];
        this.queryParams.brandList = this.brandList;

        return;
        let result = this.transformData(list);
        this.cascadeList = result;
        this.dataForm.name = [
          result[0].label,
          result[0].children[0].label,
          // result[0].children[0].children[0].label,
        ];
      });
    },
    //店铺渠道品牌转换

    transformData(data) {
      let result = [];

      data.forEach((item) => {
        let brand = item.brand;
        let channel = item.channel;
        // let shopName = item.channelShopName;

        // 如果brand在结果数组中不存在，则创建一个新的数组
        let brandIndex = result.findIndex(
          (brandObj) => brandObj.label === brand
        );
        if (brandIndex === -1) {
          result.push({
            label: brand,
            value: brand,
            children: [],
            disabled: true,
          });
          brandIndex = result.length - 1;
        }

        // 如果channel在当前brand的children数组中不存在，则创建一个新的数组
        let channelIndex = result[brandIndex].children.findIndex(
          (channelObj) => channelObj.label === channel
        );
        if (channelIndex === -1) {
          result[brandIndex].children.push({
            label: channel,
            value: channel,
            children: [],
          });
          channelIndex = result[brandIndex].children.length - 1;
        }

        // 如果shopName在当前channel的children数组中不存在，则创建一个新的数组
        // let shopIndex = result[brandIndex].children[
        //   channelIndex
        // ].children.findIndex((shopObj) => shopObj.label === shopName);
        // if (shopIndex === -1) {
        //   result[brandIndex].children[channelIndex].children.push({
        //     label: shopName,
        //     value: shopName,
        //     // children: []
        //   });
        // }
      });

      return result;
    },
    // 打开加载层
    openLoading1() {
      this.$modal.loading("正在加载数据，请稍候！");
    },
    /** 刷新缓存按钮操作 Warning*/
    handleRefresh() {
      // this.$modal.msgWarning("数据正在同步，请稍候");

      // const obj = {
      //   startTime: this.timeGap.startTime,
      //   endTime: this.timeGap.endTime,
      // };
      this.openLoading1();
      synTalentData().then(() => {
        // this.$modal.msgSuccess("同步数据成功");
        this.$modal.closeLoading();
        this.getList();
        // this.$store.dispatch('dict/cleanDict');
      });
    },
    /** 查询达人直播订单列表 */
    getList() {
      this.loading = true;
      listBiLiveTalent(this.queryParams).then((response) => {
        this.BiLiveTalentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderId: null,
        talentName: null,
        talentId: null,
        commissionRate: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // this.handleQuery();
      this.queryParams.liveTypeList = [];
      this.queryParams.channelList = [];
      this.queryParams.shopList = [];
      this.getautoSelectProTypeList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加达人直播订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getBiLiveTalent(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改达人直播订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateBiLiveTalent(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBiLiveTalent(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除达人直播订单编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBiLiveTalent(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "live/BiLiveTalent/export",
        {
          ...this.queryParams,
        },
        `BiLiveTalent_${new Date().getTime()}.xlsx`
      );
    },
    handleExportCheckCost(salesGrade, liveType) {
      const obj = {
        liveType: liveType,
        salesGrade: salesGrade,
        ...this.timeObj,
      };
      this.download(
        "live/BiLiveOrder/liveProTypeCostExport",
        {
          ...obj,
        },
        `${salesGrade}_成本核算_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss" scoped>
/* 移除默认的列表样式 */
ul {
  margin-top: 0.4%;
  list-style-type: none;
  /* 设置弹性布局，使列表项横向排列 */
  display: flex;
  /* 添加一些内边距和背景颜色 */
  // padding: 10px;
  margin-right: 10px;
  /* 设置边框和圆角 */
  // border: 1px solid #ddd;
  border-radius: 5px;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
}

/* 设置列表项样式 */
li {
  /* 添加一些内边距和右边距 */
  // padding: 10px;
  margin-right: 10px;
  /* 设置链接文本样式 */
  font-size: 15px;
  color: #bbb;
  text-decoration: none;
}

li.active a {
  // color: #f00;
  /* 高亮颜色 */
  color: #fff;
  background-color: #40c9c6;
}

// section {
//   margin-top: 60px;
// }

.dashboard-editor-container {
  padding: 16px;
  // background-color: rgb(240, 242, 245);
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 16px;
  }
}

@media (max-width: 1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>